<template>
	<div class="page splitBillConfig">
		<div class="scroll-view">
			<customHeader middleTitle="分账设置" @leftCallBack="handleBack"/>
			<div class="page-body">
				<div class="split-bill-list" v-if="splitBillList">
					<div class="section-title">
						<img src="../../../static/images/splitBilllist.png" />
						<span>共计{{splitBillList.length}}个分账方</span>
					</div>
					<ul>
						<li class="item"
						v-for="(item,index) in splitBillList"
						:key="index">
							<div class="left">
								<span class="index">第{{index + 1}}个分账方</span>
								<div class="account">
									<span class="name">{{item.accountName}}</span>
									<span class="type" v-if="item.accountType == '0'">对公</span>
									<span class="type" v-if="item.accountType == '1'">对私</span>
								</div>
								<span class="blank">{{item.bankName + ' ' + item.accountNo}}</span>
							</div>
							<div class="right">
								<input class="input" type="number" v-on:input="rateChange($event, item)" v-model="item.separateRate" />
								<span class="unit">%</span>
								<span class="bottom">分账比列</span>
							</div>
							<div class="bottom">
								<span class="line"></span>
								<span class="delete" @click="showDeteleSplitBillBox(item)">
									<img src="../../../static/images/trash.png" />
									删除该分账方
								</span>
							</div>
						</li>
						<div class="addSplitBillObject">
							<span class="text" @click="addSplitBillObject()">
								<img src="../../../static/images/add.png" />
								{{ splitBillList.length > 0 ? '继续添加分账方' : '添加分账方'}}
							</span>
						</div>
					</ul>
				</div>
			</div>
			<div class="bottom-options">
				<span class="top-line"></span>
				<div class="current-store-billing-ratio">
					<span class="left">当前门店</span>
					<span v-if="shopInfo.shopName" class="middle">{{shopInfo.shopName}}</span>
					<span class="right">分账比例为{{shopInfo.totalRate}}%</span>
				</div>
				<span class="billing-ratio-info">当前门店分账比例 = 100% - 各分账方分账比例之和</span>
				<div class="btn-wrap">
					<span class="btn" :class="{disabled:disabledSubmit}" @click="submit">提交</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import { Switch, MessageBox, Toast } from "mint-ui";
Vue.component(Switch.name, Switch);

Number.prototype.add = function (arg) {
  var r1, r2, m;
  try { r1 = this.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2))
  return (this * m + arg * m) / m
}

Number.prototype.sub = function (arg) {
  return this.add(-arg);
}

export default {
  name: "billedStoreConfig",
  data() {
    return {
      shopInfo: JSON.parse(this.$route.query.shopInfo),
      splitBillList: JSON.parse(this.$route.query.splitBillList),
      disabledSubmit: true,
      isSubmit: false
    };
  },
  methods: {
    handleBack() {
      if (!this.disabledSubmit) {
        let _this = this;
        MessageBox.confirm('',{
          title:'',
          message:'<div style="text-align:center;color: #172735;font-size: 15px;font-weight: 400;line-height: 25px;margin: 20px;">分账信息有变更，是否返回？</div>',
          confirmButtonText:'留在页面',
          cancelButtonText:'返回'
        }).catch(error =>{
          _this.$router.go(-1);
        });
      }
      else {
        this.$router.go(-1);
      }
    },
    rateChange(obj, res) {
      for (let i = 0; i < this.splitBillList.length; i++) {
        const item = this.splitBillList[i];
        if (item.originSeparateRate != item.separateRate) {
          this.disabledSubmit = false;
          return;
        }
      }
      this.disabledSubmit = true;
    },
    showDeteleSplitBillBox(item) {
      let _this = this;
      MessageBox.confirm('',{
        title:'',
        message:'<div style="text-align:center;color: #172735;font-size: 15px;font-weight: 400;line-height: 25px;margin: 20px;">删除分账方后，如需分账可以重新增加分账设置</div>',
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(action => {
        if (action == 'confirm'){
          _this.closeSplitBill(item)
        }
      }).catch(error =>{

      });
    },
    getShopSplitAccount() {
      var url = "/newapp/shopSplit/queryShopSplitAccount.do";
      this.ajax({
        url: url,
        type: "post",
        data : {supplierId : this.shopInfo.supplierId, shopId : this.shopInfo.shopId},
        controlLoading: false
      })
      .then((res) => {
        this.loading = false;
        this.noMore = false;
        if (res.success) {
          res.resultObject.forEach(el => {
            if (el.separateRate == null) {
              el.separateRate = 0;
            }
            el.originSeparateRate = el.separateRate;
          });
          this.splitBillList = res.resultObject;
        } else {
          this.splitBillList = [];
        }
        this.countTotalRate();
      })
      .catch((err) => {
      });
    },
    countTotalRate() {
      var tempTotalRate = 0;
      this.splitBillList.forEach(item=>{
        tempTotalRate += item.separateRate;
      });
      this.shopInfo.totalRate = Number(100).sub(tempTotalRate);
    },
    closeSplitBill(item) {
      let _this = this;
      var url = "/newapp/shopSplit/isEnableShopSplitAccount.do";
      var params = {supplierId : this.shopInfo.supplierId, shopId : this.shopInfo.shopId, voucherNumber: item.voucherNumber, isEnable: '0'};
      this.ajax({
        url: url,
        type: 'post',
        data : params,
        controlLoading: false,
      }).then(function(res){
        if (res != null && res.success){
          Toast("删除分账方成功");
          _this.getShopSplitAccount();
        }else{
          Toast("删除分账方失败，请稍后再试");
        }
      })
      .catch(function(err){

      })
    },
    submit() {
      if (this.disabledSubmit) {
        return;
      }

      let _this = this;
      var tempArray = [];
      var totalRate = 0;
      for (let index = 0; index < this.splitBillList.length; index++) {
        const element = this.splitBillList[index];
        // if (element.originSeparateRate != element.separateRate) {
          tempArray.push({supplierId: element.supplierId,
                          shopId: element.shopId,
                          voucherNumber: element.voucherNumber,
                          separateRate:element.separateRate});
        // }
        totalRate += Number(element.separateRate);
      }
      if (totalRate > 99) {
        Toast("所有分账方费率总和不能超过99%，请修改费率");
        return;
      }

      var url = "/newapp/shopSplit/modifyShopSplitAccount.do";
      this.ajax({
        url: url,
        type: 'post',
        data : tempArray,
        controlLoading: false,
      }).then(function(res){
        if(res != null && res.success){
          Toast("修改分账比例成功");
          _this.disabledSubmit = true;
          _this.getShopSplitAccount();
        }else{
          Toast("修改分账比例失败，请稍后再试");
        }
      })
      .catch(function(err){

      })
    },
    addSplitBillObject() {
      this.$router.push({ path: "/splitBill/billedStoreConfig/addSplitBill", query: {billedStoresCount: this.splitBillList.length, shopInfo: JSON.stringify(this.shopInfo)}});
    },
  },
  created() {
    this.getShopSplitAccount();
  },
  components: {
    customHeader,
  }
};
</script>
<style lang='scss' scoped>
@import "splitBillConfig";
</style>
